<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <div class="app-container" style="display: flex;">
      <div>
        <el-card class="box-card">
        <el-form :model="queryParams" ref="queryForm" size="small"  v-show="showSearch"
               label-width="98px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入商品名称" style="width: 150px;"
                    clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="商品型号" prop="model">
          <el-input v-model="queryParams.model" placeholder="请输入商品型号" style="width: 150px;"
                    clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="商品明细" prop="brand">
          <el-input v-model="queryParams.brand" placeholder="请输入商品明细" style="width: 150px;"
                    clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <div style=" display: flex;align-items: center;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="info" icon="el-icon-upload2" size="mini" @click="showUploadDialog">导 入</el-button>
          </div>
          <div style="display: flex;align-items: center;margin-top: 30px;">

             <el-input-number v-model="form.counts" ></el-input-number>

            <el-button type="primary" size="mini" @click="submitForm">添 加</el-button>
          </div>
      </el-form>
    </el-card>
      </div>
      <div style="width: 85%;margin-left: 10px;">
        <el-card class="box-card">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-table border v-loading="loading" :data="columns" @selection-change="handleSelectionChange"
                  :max-height="400">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="商品名称" align="center" prop="name"/>
          <el-table-column align="center" label="商品类别" prop="goodsType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.goods_type" :value="scope.row.type"/>
            </template>
          </el-table-column>
          <el-table-column label="商品型号" align="center" prop="model"/>
          <el-table-column label="商品明细" align="center" prop="brand"/>
          <el-table-column label="商品单位" align="center" prop="unit"/>
          <!--<el-table-column label="含税单价(成本)" align="center" prop="costPriceTax"/>-->
          <el-table-column label="销售单价(成本)" width="210">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.costPriceTax" :precision="2"
                               :min="0"></el-input-number>
            </template>
          </el-table-column>
         <!-- <el-table-column label="订单数量" align="center" prop="counts" width="210">
             <template slot-scope="scope">
               <el-input-number v-model="scope.row.counts"
                                :min="0" ></el-input-number>
             </template>
           </el-table-column>-->
           <!-- <el-table-column label="采购数量" align="center" prop="count"/> -->
          <el-table-column label="库存数量" align="center" prop="remainderCount"/>
          <el-table-column label="销售单价" width="210">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.goodsUnitPrice" :precision="2"
                               :min="scope.row.costPriceTax" @change="handleChangeMoney(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="锁定数量" width="210">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.goodsCount" :max="scope.row.remainderCount"
                               :min="0" @change="handleChangeMoney(scope.row)" ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="发生日期" width="200">
            <template slot-scope="scope">
              <el-date-picker clearable style="width: 160px"
                              v-model="scope.row.buyDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择发生日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="销售总价" align="center" prop="goodsTotalPrice"/>
         <!-- <el-table-column label="销售总价" width="210">
            <template slot-scope="scope">
              <el-input-number disabled v-model="scope.row.goodsTotalPrice" :min="0"></el-input-number>
            </template>
          </el-table-column>-->

         <el-table-column label="剩余数量" width="210">
            <template slot-scope="scope">
              <el-input-number disabled v-model="scope.row.shengyu" :min="0"></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize" @pagination="getList"/>
                </el-card>
      </div>
    </div>
    <el-card class="box-card">
    <el-table :data="columns2" ref="dragTable" row-key="id" v-loading="loading2">
      <el-table-column align="center" label="序号" type="index" width="50">
        <template slot-scope="scope">
          <span>{{(queryParams2.pageNum - 1) * queryParams2.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品名称" prop="goodsName"/>
      <el-table-column align="center" label="商品类别" prop="goodsType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.goods_type" :value="scope.row.goodsType"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品型号" prop="model"/>
      <el-table-column align="center" label="商品单位" prop="unit"/>
      <el-table-column align="center" label="销售单价" prop="goodsUnitPrice"/>
      <el-table-column align="center" label="订单数量" prop="counts"/>
      <el-table-column align="center" label="锁定数量" prop="goodsCount"/>
      <el-table-column align="center" label="请购数量" prop="shengyu"/>
      <el-table-column align="center" label="销售总价" prop="goodsTotalPrice"/>
      <el-table-column align="center" label="销售成本" prop="goodsBuyTotal"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-popconfirm :title="`确认删除 `+scope.row.goodsName+` 数据项？`" @confirm="handleDelete(scope.row)"
                         style="margin-left: 10px;">
            <el-button icon="el-icon-delete" size="mini" slot="reference" type="text"
                       v-hasPermi="['develop:ProjectBaseInfo:remove']">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitProject" v-if="">提交订单</el-button>
      <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
      <el-button @click="cancel">取 消</el-button>
    </div>
  <upload-dialog ref="uploadDialog" @ok="getList" @handleFileSuccess="handleFileSuccess"></upload-dialog>

  </el-dialog>
</template>

<script>
   import UploadDialog from "@/views/upload/UploadDialog";
    import {addAction, deleteAction, getAction, getById, updateAction} from '@/api/manage'
    //import {insertGoodsSale} from '@/api/develop/goodsSale'
    // import { updateGoodsSale } from '@/api/develop/goodsProject'
    export default {
        name: "GoodsOrderinChose",
        dicts: ['goods_customer', 'company', 'yes_no', 'buy_type','goods_type'],
        components: {
          UploadDialog
        },
        data() {
            return {
                // 遮罩层
                title: "产品选择",
                loading: false,
                open: false,
                // 选中数组
                ids: [],
                proId: "",
                proStatus:"",
                saleType: "2",
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 入库信息管理表格数据
                dataList: [],
                columns: [],
                form: {
                  counts: null,
                },
                rules: {},
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    name: null,
                    model: null,
                    brand: null,
                    unit: null,
                    costPrice: null,
                    count: null,
                    cost: null,
                    validityTerm: null,
                    buyId: null,
                    buyName: null,
                    buyDate: null,
                    buyType: null,
                    reimburse: null,
                    supplierId: null,
                    supplierName: null,
                    params: {
                        dataFlag: "1"
                    }
                },
                queryParams2: {
                    pageNum: 1,
                    pageSize: 1000,
                    id: null,
                    name: null,
                    model: null,
                    brand: null,
                    taxNo: null,
                    addr: null,
                    tel: null,
                    bankName: null,
                    bankNo: null,
                    info: null,
                    status: "0",
                    delFlag: null,
                    createBy: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null,
                    remark: null,
                    type: "2"
                },
                total2:'',
                loading2:'',
                columns2:[],
                url: {
                    list: '/goodsOrderIn/goodsOrderIn/list',
                    remove: '/goodsOrderIn/goodsOrderIn/',
                    export: '/goodsOrderIn/goodsOrderIn/export',
                    insertForPrj: '/goodsSale/goodsSale/insertForPrj',
                    list2: '/goodsSale/goodsSale/listSaleProject',
                    remove2: '/goodsSale/goodsSale/deleteProject/',
                    submitProject: '/projectBaseInfo/projectBaseInfo/submitProject',

                },
                tableMaxHeight: window.innerHeight - 900,
            };
        },
        created() {

        },
        methods: {
          handleFileSuccess(response, file, fileList) {
            this.$refs.uploadDialog.open = false;
            this.$refs.uploadDialog.isUploading = false;
            if (response.data.code == "200") {
              this.$alert("导入数据：" + response.data.num + "条！更新数据：" +response.data.numupdate+"条！"+ response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
            } else {
              this.$alert("导入数据：" + response.data.num + "条！更新数据：" +response.data.numupdate+"条！"+ response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
            }
            this.getList();
          },
          showUploadDialog(){
            this.$refs.uploadDialog.title = "信息导入";
            this.$refs.uploadDialog.tmplName = "订单信息模板.xlsx";
            this.$refs.uploadDialog.fileName = "订单信息.xlsx";
            this.$refs.uploadDialog.uploadUrl = "/projectBaseInfo/projectBaseInfo/importData";
            this.$refs.uploadDialog.show();
          },
          getList2() {
                this.loading2 = true;
                /*getById(this.url.listBatch, this.ids).then(response => {
                  this.columns = response.rows;
                  this.total = response.total;
                  this.loading = false;
                });*/
                this.queryParams2.projectId = this.proId
                getAction(this.url.list2, this.queryParams2).then(response => {
                    this.columns2 = response.rows;
                    this.total2 = response.total;
                    this.loading2 = false;
                });
            },
          handleUpdate(row) {
                const id = row.id || this.ids;
                this.proId = id;
                this.open = true;
                this.loading = false;
                this.proStatus=row.status;
                // this.chose(this.proId, "2");
                this.getList2();

            },
            refreshPageData() {
                let that = this;
                let param = {
                    id: that.proId
                }
                that.handleUpdate(param);

            },
            handleDelete(row) {
                const ids = row.id || this.ids;
                deleteAction(this.url.remove2, ids).then(response => {
                    this.refreshPageData();
                    this.$modal.msgSuccess("删除成功");
                    this.handleQuery();
                }).catch(() => {
                });
            },
          // handleChangeCounts(row) {
          //   let that = this;
          //   let handleReckonMoney = (row) => {
          //     if(row.shengyu ==undefined || row.shengyu ==null ){
          //       let row_count = 0;
          //       row_count =row.counts- row.goodsCount;
          //       that.$set(row, 'shengyu', row_count);
          //     }else{
          //       let row_count =row.shengyu- row.goodsCount;
          //       that.$set(row, 'counts', row_count);
          //     }
          //   };
          //   handleReckonMoney(row);
          // },
            handleChangeMoney(row) {
                let that = this;
                let handleReckonMoney = (row) => {
                    let row_money = 0;
                    row_money = that.functionNumberMul(Number(row.goodsUnitPrice), Number(row.goodsCount))
                    that.$set(row, 'goodsTotalPrice', row_money);
                };
                handleReckonMoney(row);
            },
            functionNumberMul(arg1, arg2) {
                var m = 0;
                var s1 = arg1.toString();
                var s2 = arg2.toString();
                try {
                    m += s1.split(".")[1].length;
                } catch (e) {
                }
                try {
                    m += s2.split(".")[1].length;
                } catch (e) {
                }
                return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
            },
            chose(proId, type) {
                this.open = true;
                this.proId = proId;
                this.saleType = type;
                this.getList();
            },
            getList() {
                this.loading = true;
                getAction(this.url.list, this.queryParams).then(response => {
                    let res = response.rows;
                    for (let i = 0; i < res.length; i++) {
                        res[i].buyDate = new Date();
                    }
                    this.columns = res;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            // 取消按钮
            cancel() {
                this.open = false;
                // this.reset();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.dataList = selection;
                this.ids = selection.map(item => item.id)
                this.single = selection.length !== 1
                this.multiple = !selection.length
            },
            submitProject(){
                getAction(this.url.submitProject, {id:this.proId,status:"1"}).then(response => {
                this.refreshPageData();
                this.$modal.msgSuccess("提交成功!");
                this.open = false;
                this.handleQuery();
                this.$parent.getList()
              }).catch(() => {
              });
            },
            /** 提交按钮 */
            submitForm() {
                let that = this;
                if(that.form.counts && that.form.counts>=0){
                  const ids = this.ids;
                  if (ids == null || ids == '' || ids == 'undefined') {
                    that.$modal.msgError("请选择一条记录");
                    // alert("请选择一条记录");
                  } else {
                    that.$refs["form"].validate(valid => {
                      if (valid) {
                        const goodsOrderIn = Object.assign({});
                        goodsOrderIn.projectId = that.proId;
                        goodsOrderIn.type = that.saleType;
                        goodsOrderIn.counts = that.form.counts;
                        goodsOrderIn.columns = that.dataList;
                        addAction(that.url.insertForPrj, goodsOrderIn).then(response => {
                          that.$modal.msgSuccess("添加成功");
                          // this.open = false;
                          that.$emit('ok');
                          // this.queryParams2.pageNum = 1
                          // this.queryParams2.pageSize = 1000
                          that.getList2();
                          that.handleQuery();
                        });
                        /*insertGoodsSale(goodsOrderIn).then(res => {
                          that.$modal.msgSuccess(res.msg);
                          if (res.code === 200) {
                            that.$modal.msgSuccess("修改完成！");
                            that.open = false;
                            that.$emit('ok');
                          }
                        });*/
                      }
                    });
                    /*const goodsOrderIn = Object.assign({});
                    goodsOrderIn.projectId = this.proId;
                    goodsOrderIn.ids=ids.toString();
                    insertGoodsSale(goodsOrderIn).then(res => {
                      if (res.code === 200) {
                        this.open = false;
                        this.$emit('ok');
                      }
                    });*/
                  }
                }else{
                  that.$modal.msgError("请填写该订单的产品数量!");
                }

            },
        }
    };
</script>
